package org.yzbdl.lanius.util;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.version.BuildVersion;
import org.yzbdl.lanius.authorize.verification.LicenseVerification;

import java.io.UnsupportedEncodingException;

public class LaunchUtils {

    /**
     * 打印厂商信息
     */
    private static boolean PRINT_ABOUT = false;

    /**
     * 检查授权
     *
     * @throws Exception
     */
    public static void checkLicAndShowInfo() throws KettleException {
        if (LicenseVerification.LICENSE_HAS_CHECK) { // 判断是否已经进行过授权检查
            return;
        }
        LicenseVerification.LICENSE_HAS_CHECK = true;
        try {

            // 授权文件是否存在
            if (ObjectUtil.isNotEmpty(LicenseVerification.getLicense())) {
                // 检查授权状态 设置启动模式为商业版本
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        LicenseVerification.activeEntMode(LicenseVerification.checkLicense(VersionUtil.getLaniusTopVersion(), VersionUtil.getLaniusVersionTopTwo()));
                        LicenseVerification.finishCheckMode(true);
                    }
                }).start();

                // 更新BuildVersion中的产品名称 不论是否有效
                BuildVersion buildVersion = BuildVersion.getInstance();
                // buildVersion.setProductName(ACTIVE_ENTERPRISE_EDITION ? getProductLanius() :
                // getCommunityLanius());
                // buildVersion.setScheduleName(ACTIVE_ENTERPRISE_EDITION ? getProductSchedule() :
                buildVersion.setProductName(Const.getProductLanius());
                // 获取来自license中的授权对象
                buildVersion.setLicenseTo(LicenseVerification.license.getCustomerInfo());
                // 获取来自Lic中的信息
                Const.FUNCTION_POINT = LicenseVerification.license.getCertificationFunction();
            }

            // 命令界面打印厂商信息
            LaunchUtils.showAboutToConsole();
        } catch (Exception e) {
            throw new KettleException(e);
        }
    }

    /**
     * 输出客户端启动信息
     * 必须先校验License
     */
    public static void showAboutToConsole() throws UnsupportedEncodingException {
        if (!LaunchUtils.PRINT_ABOUT) {
            try {
                Console.log();
                BuildVersion.getInstance().showInfoToConsole();
                Console.log();
                LaunchUtils.PRINT_ABOUT = true;
            } catch (UnsupportedEncodingException e) {
                Console.error("版本信息显示错误：" + e);
            }
        }
    }

}
